const express = require('express');
const router = express.Router();
const { Geocode } = require('../models');
const { Op } = require('sequelize');

// 模拟延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// GET /api/geocode - 获取地理编码信息
router.get('/', async (req, res) => {
  try {
    const { address, location, type = 'geo' } = req.query;
    
    // 模拟网络延迟
    await delay(300);
    
    let whereClause = { type };
    
    if (address) {
      whereClause.address = {
        [Op.like]: `%${address}%`
      };
    }
    
    if (location) {
      whereClause.location = {
        [Op.like]: `%${location}%`
      };
    }
    
    const geocodeData = await Geocode.findOne({
      where: whereClause,
      order: [['id', 'DESC']]
    });
    
    if (!geocodeData) {
      return res.status(404).json({
        success: false,
        message: '未找到地理编码数据'
      });
    }
    
    const response = {
      success: true,
      data: {
        status: '1',
        info: 'OK',
        infocode: '10000',
        count: '1',
        geocodes: [{
          formatted_address: geocodeData.formatted_address,
          country: '中国',
          province: geocodeData.province,
          city: geocodeData.city,
          citycode: '020',
          district: geocodeData.district,
          adcode: geocodeData.adcode,
          township: '',
          neighborhood: {
            name: '',
            type: ''
          },
          building: {
            name: '',
            type: ''
          },
          number: geocodeData.number,
          street: geocodeData.street,
          level: geocodeData.level,
          location: geocodeData.location
        }]
      },
      message: '获取地理编码信息成功'
    };
    
    res.json(response);
  } catch (error) {
    console.error('地理编码API错误:', error);
    res.status(500).json({
      success: false,
      message: '获取地理编码信息失败',
      error: error.message
    });
  }
});

// GET /api/geocode/regeo - 逆地理编码
router.get('/regeo', async (req, res) => {
  try {
    const { location } = req.query;
    
    await delay(200);
    
    const geocodeData = await Geocode.findOne({
      where: {
        location: {
          [Op.like]: `%${location}%`
        },
        type: 'regeo'
      },
      order: [['id', 'DESC']]
    });
    
    if (!geocodeData) {
      return res.status(404).json({
        success: false,
        message: '未找到逆地理编码数据'
      });
    }
    
    const response = {
      success: true,
      data: {
        status: '1',
        info: 'OK',
        infocode: '10000',
        regeocode: {
          formatted_address: geocodeData.formatted_address,
          addressComponent: {
            country: '中国',
            province: geocodeData.province,
            city: geocodeData.city,
            citycode: '020',
            district: geocodeData.district,
            adcode: geocodeData.adcode,
            township: '',
            neighborhood: {
              name: '',
              type: ''
            },
            building: {
              name: '',
              type: ''
            },
            streetNumber: {
              street: geocodeData.street,
              number: geocodeData.number,
              location: geocodeData.location,
              direction: '',
              distance: ''
            }
          },
          pois: [],
          roads: [],
          roadinters: [],
          aois: []
        }
      },
      message: '获取逆地理编码信息成功'
    };
    
    res.json(response);
  } catch (error) {
    console.error('逆地理编码API错误:', error);
    res.status(500).json({
      success: false,
      message: '获取逆地理编码信息失败',
      error: error.message
    });
  }
});

// GET /api/geocode/geo - 地理编码
router.get('/geo', async (req, res) => {
  try {
    const { address } = req.query;
    
    await delay(250);
    
    const geocodeData = await Geocode.findOne({
      where: {
        address: {
          [Op.like]: `%${address}%`
        },
        type: 'geo'
      },
      order: [['id', 'DESC']]
    });
    
    if (!geocodeData) {
      return res.status(404).json({
        success: false,
        message: '未找到地理编码数据'
      });
    }
    
    const response = {
      success: true,
      data: {
        status: '1',
        info: 'OK',
        infocode: '10000',
        count: '1',
        geocodes: [{
          formatted_address: geocodeData.formatted_address,
          country: '中国',
          province: geocodeData.province,
          city: geocodeData.city,
          citycode: '020',
          district: geocodeData.district,
          adcode: geocodeData.adcode,
          township: '',
          neighborhood: {
            name: '',
            type: ''
          },
          building: {
            name: '',
            type: ''
          },
          number: geocodeData.number,
          street: geocodeData.street,
          level: geocodeData.level,
          location: geocodeData.location
        }]
      },
      message: '获取地理编码信息成功'
    };
    
    res.json(response);
  } catch (error) {
    console.error('地理编码API错误:', error);
    res.status(500).json({
      success: false,
      message: '获取地理编码信息失败',
      error: error.message
    });
  }
});

module.exports = router; 